package org.example.service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import javafx.scene.input.MouseDragEvent;
import lombok.val;
import org.apache.commons.beanutils.PropertyUtils;
import org.example.dto.RoleDto;
import org.example.dto.SysRoleDto;
import org.example.entity.SysDept;
import org.example.entity.SysMenu;
import org.example.entity.SysRole;
import org.example.entity.SysRoleMenu;
import org.example.mapper.SysMenuMapper;
import org.example.mapper.SysRoleMapper;
import org.example.mapper.SysRoleMenuMapper;
import org.example.model.MenuModel;
import org.example.model.RoleModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;


    //获取用户列表
    public List<SysRole> getAll(){
        return  sysRoleMapper.selectList(null);

    }

    public List<SysRole> getMenuByRole(Integer id){

//        System.out.println("service-role-menu-byId----->"+sysRoleMapper.getMenuByRole(id));

        return sysRoleMapper.getMenuByRole(id);

    }

    //删除和插入
    public void delMenuByRole(RoleDto roleDto) {

        //（1）删除role表数据、（2）role在menu里的权限
//        sysRoleMapper.delRoles(roleDto.getId());

        System.out.println("service1-roleDto"+roleDto);

        sysRoleMapper.delMenuDataByRole(roleDto.getId());





//        sysRoleMapper.insertBatchMenu(roleDto);

        System.out.println("service2-roleDto"+roleDto);



        List<MenuModel> ids = roleDto.getIds();

        ids.stream().forEach(i->{
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(Long.valueOf(i.getId()));
            sysRoleMenu.setRoleId(Long.valueOf(roleDto.getId()));
            sysRoleMenuMapper.insert(sysRoleMenu);
            System.out.println("i "+i);

        });


        System.out.println("service2-roleDto.getId()"+roleDto.getId());

        //插入数据

    }

    //回显操作
    public SysRole getById(Integer id) {
        return sysRoleMapper.selectById(id);
    }


    public List<MenuModel> getRoleTree(String name) {
        // 查询对应的用户的所有的权限

//        System.out.println("name--->"+name);

        List<SysMenu> sysMenuList = sysRoleMapper.getRoleByTree(name);
//        System.out.println("role-menu下的递归树结果为：--------------->"+sysMenuList);

//        System.out.println("xx-----");
//        sysMenuList.forEach(i->{
//            System.out.println(i);
//        });
//        System.out.println("xx-----");
//        System.out.println("role-root------>"+rootMenuModel);

        List<MenuModel> rootMenuModels = sysMenuList.stream()
                .filter(sm -> sm.getType() == 0 )
                .map(this::convertSysMenuToModelModel).collect(Collectors.toList());

//        System.out.println("role-menu-filter下的递归树结果为：--------------->"+rootMenuModels);

        // 构建递归树， 据顶级菜单往下挂儿子菜单或者孙子菜单；
        generateRecursionRoutes(rootMenuModels, sysMenuList);



//        System.out.println("role-menu-root下的递归树结果为：--------------->"+rootMenuModels);
        return rootMenuModels;
    }

    /**
     * 构建递归路由信息
     * @param menuModels
     * @param sysMenuList
     */
    private void generateRecursionRoutes(List<MenuModel> menuModels, List<SysMenu> sysMenuList) {
        // null == menuModels || menuModels.isEmpty()
        if(!CollectionUtils.isEmpty(menuModels)) {
            // 循环获取每个路由，然后挂儿子路由: 儿子的parentId == 等于它的id
            menuModels.forEach(m -> {
                // 获取当前路由的id, 根据id找儿子(儿子的parentId为当前路由的id)
                Integer id = m.getId();

                List<MenuModel> children = sysMenuList.stream()
//                        .filter(sm -> !sm.getType().equals(2))
                        .filter(sm -> sm.getParentId().equals(id))
                        .map(this::convertSysMenuToModelModel).collect(Collectors.toList());

//                System.out.println("children:"+children);
                if(!CollectionUtils.isEmpty(children)) {
                    // 将儿子路由塞进去
                    m.setChildren(children);
                    // 接着构建儿子的后代路由
                    generateRecursionRoutes(children, sysMenuList);
                }
            });
        }
    }

    /**
     * 1.将 SysMenu对象转换为 MenuModel对象
     * MenuModel将来对应的json:
     *   {
     *      path: 'dept',
     *      name: 'DepartmentManager',
     *      component: () => import('@/views/dept/index'),
     *      meta: { title: '部门管理', icon: 'tree' }
     *    }
     */
    private MenuModel convertSysMenuToModelModel(SysMenu sysMenu) {

//        RoleModel model = new RoleModel();

        MenuModel.Meta meta = new MenuModel.Meta();
        MenuModel model = new MenuModel();
        List<String> label = new ArrayList<String>();




        try {
            PropertyUtils.copyProperties(meta, sysMenu);
            PropertyUtils.copyProperties(model, sysMenu);
            model.setMeta(meta);

//            System.out.println("model--->"+model);
            // 0表示顶级菜单，定义菜单的 component是 Layout; 儿子菜单的 component的值不是 “Layout”
            if(0 == sysMenu.getType()) {
                model.setName(meta.getTitle());
                label.add(model.getName());
                label.add(model.getPath());
                if (model.getType()==0){
                    model.setComponent("目录");
                    model.setTop("顶级菜单");

                }else if (model.getType()==1){
                    model.setComponent("菜单");

                }else if (model.getType()==2){
                    model.setComponent("按钮");

                }

//                String disable;
//                if(model.getHidden()){
//                    disable = "true";
//
//                }else{
//                    disable = "false";
//
//
//                }
//                label.add(disable);
//                model.setLabelList(label);

//                label.add(model.get)

            }else {
                model.setName(meta.getTitle());
                label.add(model.getName());
                label.add(model.getPath());
                model.setLabelList(label);

                if (model.getType()==0){
                    model.setComponent("目录");


                }else if (model.getType()==1){
                    model.setComponent("菜单");

                }else if (model.getType()==2){
                    model.setComponent("按钮");

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;


    }

    //添加用户
    public void addRole(SysRoleDto sysRoleDto){
        sysRoleMapper.insert(sysRoleDto);
    }

    //更具id查找部门信息编辑页面回显
//    public SysRole getById(Integer id){
//        return sysRoleMapper.selectById(id);
//    }

    //编辑角色
    public  void editRole(SysRoleDto sysRoleDto){
        sysRoleDto.setCreateTime(new Date());
        sysRoleMapper.updateById(sysRoleDto);
    }

    //删除角色
    public void deleteById(Long id){
        // deleteById() 一定通过 @TableId 来表示谁是id
        sysRoleMapper.deleteById(id);

        sysRoleMenuMapper.deleteByRoleId(id);
    }
}
